/**
 * New node file
 */
var mongodb = require('./db');

function Article(name,title,articleType,contents){
	this.name = name;
	this.title = title;
	this.articleType = articleType
	this.contents = contents;
}

module.exports = Article;

Article.prototype.save = function(callback){
	var date = new Date();
	var time = {
		date:date,
		year:date.getFullYear(),
		month:date.getFullYear()+"-"+(date.getMonth()+1),
		day:date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),
		minute:date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes()
	};
	//要存入数据库的文档
	var article = {
		name:this.name,
		time:time,
		title:this.title,
		article:this.article
	};
	//打开数据库
	mongodb.open(function(err,db){
		if(err){
			return callback(err);
		}
		//读取 articles 集合
		db.collection('articles',function(err,collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			//将文档插信 articles 集合
			collection.insert(article,{
				safe:true
			},function(err,article){
				mongodb.close();
				callback(null);
			});
		});
	});
};

Article.get = function(name,callback){//读取文章及其相关信息
	//打开数据库
	mongodb.open(function(err,db){
		if(err){
			return callback(err);
		}
		//读取 articles 集合
		db.collection('articles',function(err,collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			var query = {};
			if(name){
				query.name = name;
			}
			//根据 query 对象查询文章
			collection.find(query).sort({
				time:-1
			}).toArray(function(err,docs){
				mongodb.close();
				if(err){
					callback(err,null);//失败！返回 null
				}
				callback(null, docs);//成功！以数组形式返回查询的结果
			});
		});
	});
	
};